import os
from git.repo import Repo
import json

RED_OP = "\033[31m{}\033[0m"
GREEN_OP = "\033[32m{}\033[0m"
YELLOW_OP = "\033[33m{}\033[0m"
BLUE_OP = "\033[34m{}\033[0m"
DEFAULT_OP = "\033[38m{}\033[0m"


def reset():
    for path, dir_list, file_list in os.walk(
        os.path.join(os.path.expanduser("~"), "shell/com/yapai/project")
    ):
        for file_name in file_list:
            with open(os.path.join(path, file_name), "r") as load_file:
                proJson = json.load(load_file)
                sub_fd_name = proJson["project_name"]
                branch_name = proJson["branch_name"]
                project_fd = os.path.join(
                    os.path.expanduser("~"), "temp", "yapai", sub_fd_name
                )
                if os.path.exists(project_fd) is False:
                    continue
                print(project_fd)
                repo = Repo(project_fd)
                diffLine = repo.git.diff(
                    repo.active_branch, "origin/{}".format(repo.active_branch)
                )
                if repo.is_dirty() is True or len(diffLine) > 0:
                    repo.git.reset("--hard", "origin/{}".format(repo.active_branch))
                if branch_name != str(repo.active_branch):
                    print(
                        RED_OP.format("CURRENT BRANCH STATUS = ")
                        + GREEN_OP.format(repo.active_branch)
                    )
                    repo.git.checkout(branch_name)
                    repo.git.pull()
                else:
                    print(
                        YELLOW_OP.format("CURRENT BRANCH STATUS = ")
                        + GREEN_OP.format(repo.active_branch)
                    )


reset()
